package cn.edu.zstu.overlappingdisappear.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.regex.Pattern;

import cn.edu.zstu.overlappingdisappear.R;
import cn.edu.zstu.overlappingdisappear.api.UserApi;
import cn.edu.zstu.overlappingdisappear.base.App;
import cn.edu.zstu.overlappingdisappear.base.BaseActivity;
import cn.edu.zstu.overlappingdisappear.base.LocalHelper;
import cn.edu.zstu.overlappingdisappear.base.MyApplication;
import cn.edu.zstu.overlappingdisappear.bean.UserBean;

public class UserActivity extends BaseActivity implements View.OnClickListener {
    private EditText etUsername,etPwd,etNickname,etRePwd;
    private TextView btnForget;
    private TextView btnRegister;
    private Button btnLogin;
    private TextView tvTip;

    //标记是否是注册界面
    private static boolean isRegist=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        initView();
    }

    private void initView() {

        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.tv_register);
        btnForget=findViewById(R.id.tv_forgetkey);
        tvTip=findViewById(R.id.tv_tip);

        etUsername = findViewById(R.id.et_username);
        etPwd = findViewById(R.id.et_key);

        etNickname = findViewById(R.id.et_nickname);
        etRePwd = findViewById(R.id.et_rekry);

        refreshView();

        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);

        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(isRegist) tvTip.setText("");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(isRegist){
                    String name = editable.toString();
                    if (name.length() < 1) return;
                    if (name.length() >= 11) {
//                    etUsername.setText(name=name.substring(0,11));
                        if (Pattern.matches("^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", name)) {

                            UserApi.usernameExist(name, new UserApi.VolleyStrHandler() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Toast.makeText(MyApplication.getInstance(), "网络连接异常", Toast.LENGTH_LONG).show();
                                    return;
                                }

                                @Override
                                public void onResponse(String responseStr) {
                                    try {
                                        JSONObject reponse = new JSONObject(responseStr);
                                        int status = reponse.getInt("code");
                                        if (status == 1) {
                                            //   存在用户
                                            tvTip.setText("用户名已存在");
                                            tvTip.setVisibility(View.VISIBLE);
                                        } else
                                            tvTip.setVisibility(View.GONE);
                                    } catch (Exception e) {

                                    }
                                }
                            });
                        } else {
                            tvTip.setText("用户名输入有误");
                            tvTip.setVisibility(View.VISIBLE);

                        }
                    }
                }
            }
        });
        if(LocalHelper.getIsLogin()){
            App.Username = LocalHelper.getUsername();
            App.Nickname = LocalHelper.getNickname();
            Intent it = new Intent(UserActivity.this,MenuActivity.class);
            startActivity(it);
            finish();
        }
    }

    //切换登录&注册界面
    private void refreshView() {
        if(isRegist){
            //注册界面
            etNickname.setVisibility(View.VISIBLE);
            etNickname.setText("");
            etUsername.setText("");
            etPwd.setText("");
            etRePwd.setText("");
            etRePwd.setVisibility(View.VISIBLE);
            btnForget.setVisibility(View.GONE);
            btnLogin.setText("注册");
            btnRegister.setText("返回");
        }else{
            //登录界面
            etNickname.setVisibility(View.GONE);
//            etUsername.setText("");
//            etPwd.setText("");
            etRePwd.setVisibility(View.GONE);
            btnForget.setVisibility(View.VISIBLE );
            btnLogin.setText("登录");
            btnRegister.setText("注册");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
          case R.id.btn_login: login(); break;
          case R.id.tv_register:register();break;
        }
    }
//15750505896
    private void register() {
        isRegist=!isRegist;
        refreshView();
    }

    private void login() {
        final String userName = etUsername.getText().toString();
        String pwd = etPwd.getText().toString();
        String nickname = etNickname.getText().toString();


        if(isRegist){

            String repwd = etRePwd.getText().toString();
            if(!pwd.equals(repwd)) Toast.makeText(MyApplication.getInstance(),"密码不一致", Toast.LENGTH_LONG).show();

            //final String username, final String password, final String nickname, VolleyStrHandler handler
            UserApi.register(userName, pwd, nickname, new UserApi.VolleyStrHandler() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MyApplication.getInstance(),"网络连接异常", Toast.LENGTH_LONG).show();
                    return;
                }

                @Override
                public void onResponse(String responseStr) {
                    try {
                        JSONObject reponse = new JSONObject(responseStr);
                        int status = reponse.getInt("code");
                        String msg=reponse.getString("msg");
                        if (status == 1) {
                            Toast.makeText(MyApplication.getInstance(),"注册成功", Toast.LENGTH_LONG).show();
                            register();
                        }else
                            Toast.makeText(MyApplication.getInstance(),msg, Toast.LENGTH_LONG).show();
                    } catch (Exception e) {

                    }
                }
            });
        }
        else
            UserApi.login(userName, pwd, new UserApi.VolleyStrHandler() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MyApplication.getInstance(),"网络连接异常", Toast.LENGTH_LONG).show();
                    return;
                }

                @Override
                public void onResponse(String responseStr) {
                    try {
                        JSONObject reponse = new JSONObject(responseStr);
                        int status = reponse.getInt("code");
                        String msg=reponse.getString("msg");
                        if (status == 1) {
                            JSONObject data = reponse.getJSONObject("data");
                            UserBean user = new Gson().fromJson(data.toString(), new TypeToken<UserBean>() {
                            }.getType());
                            App.Username = user.getUername();
                            App.Nickname = user.getNickname();
                            LocalHelper.setUserInfo(App.Username,App.Nickname);
                            LocalHelper.setIsLogin(true);
                            Intent it = new Intent(UserActivity.this,MenuActivity.class);
                            startActivity(it);
                        }else
                            Toast.makeText(MyApplication.getInstance(),msg, Toast.LENGTH_LONG).show();
                    } catch (Exception e) {

                    }
                }
            });
    }
}
